package com.ruoyi.databases.controller;

import com.alibaba.druid.DbType;
import com.alibaba.druid.pool.DruidConnectionHolder;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.databases.pojo.DatabaseVO;
import com.ruoyi.databases.pojo.DynamicSQL;
import com.ruoyi.databases.service.DatabaseService;
import com.ruoyi.framework.datasource.DynamicDataSource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("databases")
public class DatabaseController extends BaseController {

    @Resource
    private DatabaseService databaseService;
    @Resource
    private DruidDataSource druidDataSource;

    @GetMapping("list")
    public TableDataInfo list(){
        List<DatabaseVO> strings = databaseService.selectList();
        return getDataTable(strings);
    }

    @PostMapping("add")
    public AjaxResult add(@RequestParam("dbname") String dbname){
        List<DatabaseVO> databaseVOS = databaseService.selectList();
        for (DatabaseVO databaseVO:databaseVOS
             ) {
            if (databaseVO.equals(dbname)){
                return AjaxResult.error("数据库："+dbname+"已存在");
            }
        }

        String params = "CREATE DATABASE IF NOT EXISTS "+dbname+" default charset utf8 COLLATE utf8_general_ci;";
        DynamicSQL dynamicSQL = new DynamicSQL();
        dynamicSQL.setParams(params);
        databaseService.addDatabase(dynamicSQL);
        return AjaxResult.success("新增成功");
    }


    @PostMapping("change")
    public AjaxResult change(){

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setDbType(DbType.mysql);
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior" +
                "=convertToNull&useSSL=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true");
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("MASTER", druidDataSource);
        new DynamicDataSource(druidDataSource, targetDataSources);
        return AjaxResult.success();
    }


}
